<?php
namespace SimpleMVC\lib;

class PdoConnection {
    
    private $pdo;
    
    public function __construct($dsn, $user, $pwd)
    {
        $options = array(
            \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
            \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
            \PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'
        );
        $this->pdo = new \PDO($dsn, $user, $pwd, $options);
    }
    
    private function bindValues($statement, $bindings)
    {
        foreach ($bindings as $key => $value) {
            $statement->bindValue(
                is_string($key) ? $key : $key + 1,
                $value,
                is_int($value) ? \PDO::PARAM_INT : \PDO::PARAM_STR
                );
        }
    }
    
    public function getAll($sql, array $bindings = array())
    {
        $statement = $this->pdo->prepare($sql);
        if ($bindings) {
            $this->bindValues($statement, $bindings);
        }
        $statement->execute();
        return $statement->fetchAll();
    }
    
    public function getRow($sql, array $bindings = array())
    {
        $statement = $this->pdo->prepare($sql);
        if ($bindings) {
            $this->bindValues($statement, $bindings);
        }
        $statement->execute();
        $row = $statement->fetch();
        $statement->closeCursor();
        return $row ? $row : null;
    }
    
    public function getOne($sql, array $bindings = array())
    {
        $row = $this->getRow($sql, $bindings);
        return $row ? reset($row) : null;
    }
    
    public function getCol($sql, array $bindings = array())
    {
        $rows = $this->getAll($sql, $bindings);
        $cols = array();
        foreach ($rows as $row) {
            $cols[] = reset($row);
        }
        return $cols;
    }
    
    public function execute($sql, array $bindings = array())
    {
        $statement = $this->pdo->prepare($sql);
        if ($bindings) {
            $this->bindValues($statement, $bindings);
        }
        $statement->execute();
        return $statement->rowCount();
    }
    
    public function lastInsertId($name = null)
    {
        return $this->pdo->lastInsertId($name);
    }
    
    public function beginTransaction()
    {
        $this->pdo->beginTransaction();
    }
    
    public function commit()
    {
        $this->pdo->commit();
    }
    
    public function rollBack()
    {
        try {
            $this->pdo->rollBack();
        } catch (\Exception $e) {
            
        }
    }
    
    public function getPdo()
    {
        return $this->pdo;
    }
    
}
